package com.wip.reportingclient.services.impls;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import com.wip.reportingclient.services.interfaces.IZippingService;

@Service
public class ZippingServiceImpl implements IZippingService {

	public void writeZip(HttpServletResponse response,
			Map<String, ByteArrayOutputStream> bosMap) {
		response.setContentType("application/zip");
		response.addHeader("Content-Disposition",
				"attachment; filename=\"Performances.zip\"");
		response.addHeader("Content-Transfer-Encoding", "binary");
		ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();

		compress(outputBuffer, bosMap);
		try {
			response.getOutputStream().write(outputBuffer.toByteArray());
			response.getOutputStream().flush();
			outputBuffer.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	
	@Override
	public void compress(OutputStream out,
			Map<String, ByteArrayOutputStream> bosMap) {
		ZipOutputStream zipOutputStream = new ZipOutputStream(out);
		zipOutputStream.setLevel(ZipOutputStream.STORED);

		/*
		 * for (HSSFWorkbook workbook : workbooks) { ByteArrayOutputStream bos =
		 * new ByteArrayOutputStream(); try { workbook.write(bos); } catch
		 * (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */

		for (String fileName : bosMap.keySet()) {
			byte[] oneFileContent = bosMap.get(fileName).toByteArray();
			addOneFileToZipArchive(zipOutputStream, fileName, oneFileContent);
		}
		// }

		try {
			zipOutputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	void addOneFileToZipArchive(final ZipOutputStream zipStream,
			String fileName, byte[] content) {
		ZipEntry zipEntry = new ZipEntry(fileName);
		try {
			zipStream.putNextEntry(zipEntry);
			zipStream.write(content);
			zipStream.closeEntry();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
